using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CollabApp.Domain.Entities.Auth;
using CollabApp.Domain.Entities;
using CollabApp.Domain.Repositories;
using CollabApp.Domain.Services.Users;
using System.Threading;

namespace CollabApp.Application.Services.Users;

public class UserService : IUserService
{
    private readonly IRepository<User> _userRepo;
    private readonly IRepository<UserStatistics> _statsRepo;
    private readonly IRepository<Ranking> _rankingRepo;
    
    public UserService(IRepository<User> userRepo, IRepository<UserStatistics> statsRepo, IRepository<Ranking> rankingRepo)
    {
        _userRepo = userRepo;
        _statsRepo = statsRepo;
        _rankingRepo = rankingRepo;
    }

    public async Task<dynamic> UpdateAvatarAsync(Guid userId, string avatar)
    {
        // 参数校验
        if (userId == Guid.Empty)
        {
            return new { Code = 1001, Message = "参数错误：userId为空", Data = (object?)null };
        }
        if (string.IsNullOrWhiteSpace(avatar))
        {
            return new { Code = 1002, Message = "参数错误：头像不能为空", Data = (object?)null };
        }

        // 查询用户
        var user = await _userRepo.GetByIdAsync(userId);
        if (user == null)
        {
            return new { Code = 1003, Message = "用户不存在！", Data = (object?)null };
        }

        // 更新头像（像注册时一样直接传递avatar字符串）
        user.UpdateProfile(user.Nickname, avatar);
        await _userRepo.UpdateAsync(user);
        await _userRepo.SaveChangesAsync(CancellationToken.None);

        return new { Code = 1000, Message = "头像更新成功！", Data = (object?)null };
    }

    public async Task<dynamic> GetPersonalOverviewAsync(Guid userId)
    {
        if (userId == Guid.Empty)
        {
            return new { Code = 1002, Message = "参数错误：userId为空", Data = (object?)null };
        }
        var user = await _userRepo.GetByIdAsync(userId);
        if (user == null)
        {
            return new { Code = 1001, Message = "用户不存在", Data = (object?)null };
        }
        var stats = await _statsRepo.GetSingleAsync(s => s.UserId == userId);
        
        // 从Ranking表获取总积分（TotalScore类型，无限期）
        var totalScoreRanking = await _rankingRepo.GetSingleAsync(r => 
            r.UserId == userId && 
            r.RankingType == RankingType.TotalScore &&
            r.PeriodStart == DateTime.MinValue && 
            r.PeriodEnd == DateTime.MaxValue);
        
        var data = new
        {
            UserId = userId,
            AvatarUrl = user.AvatarUrl,
            Username = user.Username,
            Status = user.Status.ToString(),
            TotalScore = totalScoreRanking?.Score ?? 0,
            TotalGames = stats?.TotalGames ?? 0,
            TotalPlayTimeSeconds = stats?.TotalPlayTime ?? 0
        };
        return new { Code = 1000, Message = "请求个人中心成功", Data = data };
    }

    public async Task<dynamic> ChangePasswordAsync(Guid userId, string currentPassword, string newPassword, string confirmNewPassword)
    {
        // 参数校验
        if (userId == Guid.Empty)
        {
            return new { Code = 1001, Message = "参数错误：userId为空", Data = (object?)null };
        }
        if (string.IsNullOrWhiteSpace(currentPassword) || string.IsNullOrWhiteSpace(newPassword) || string.IsNullOrWhiteSpace(confirmNewPassword))
        {
            return new { Code = 1002, Message = "参数错误：密码不能为空", Data = (object?)null };
        }
        if (newPassword.Length < 6 || newPassword.Length > 20)
        {
            return new { Code = 1003, Message = "新密码长度需为6-20个字符！", Data = (object?)null };
        }
        if (newPassword != confirmNewPassword)
        {
            return new { Code = 1004, Message = "两次输入的新密码不一致！", Data = (object?)null };
        }

        // 查询用户
        var user = await _userRepo.GetByIdAsync(userId);
        if (user == null)
        {
            return new { Code = 1005, Message = "用户不存在！", Data = (object?)null };
        }

        // 校验当前密码
        if (!user.VerifyPassword(currentPassword))
        {
            return new { Code = 1006, Message = "当前密码不正确！", Data = (object?)null };
        }

        // 更新密码
        user.UpdatePassword(newPassword);
        await _userRepo.UpdateAsync(user);
        await _userRepo.SaveChangesAsync(CancellationToken.None);

        return new { Code = 1000, Message = "密码修改成功！", Data = (object?)null };
    }
}